package com.dk.server;

import com.alibaba.fastjson2.JSONObject;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Server {

    public static void main(String[] args) {
        System.out.println("Server start");
        try{
            //创建ServerSocket
            ServerSocket serverSocket = new ServerSocket(9001);
            while (true){
                //接受socket请求
                Socket socket = serverSocket.accept();
                new Thread(new Server_listen(socket)).start();
                new Thread(new Server_send(socket)).start();
            }
        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
class Server_listen implements Runnable{
private Socket socket;
Server_listen(Socket socket)
{
    this.socket = socket;
}
@Override
    public void run() {
    try{
        ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
        while (true){
            System.out.println(objectInputStream.readObject());
        }

    }catch (Exception e)
    {
        e.printStackTrace();
    }
}
}


class Server_send implements Runnable{

private Socket socket;
Server_send(Socket socket)
{
    this.socket = socket;
}
@Override
    public void run() {
    try{
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
        Scanner scanner = new Scanner(System.in);
        while (true){
            System.out.println("服务端，请输入：");
            String string = scanner.nextLine();

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "msg");
            jsonObject.put("content", string);
            objectOutputStream.writeObject(jsonObject);
            objectOutputStream.flush();
        }
        } catch (Exception e) {
        e.printStackTrace();
    }
    }
}